package livechat;

import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.*;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;

class ObjectReturn {
	private int _iCode;
	private Vector<ChatLog> _vChatLog;
	private long _lTime;
	ObjectReturn(int iCode, Vector<ChatLog> vChatLog, long lTime) {
		set_iCode(iCode);
		set_vChatLog(vChatLog);
		set_lTime(lTime);
	}
	public int get_iCode() {
		return _iCode;
	}
	public void set_iCode(int _iCode) {
		this._iCode = _iCode;
	}
	public Vector<ChatLog> get_vChatLog() {
		return _vChatLog;
	}
	public void set_vChatLog(Vector<ChatLog> _vChatLog) {
		this._vChatLog = _vChatLog;
	}
	public long get_lTime() {
		return _lTime;
	}
	public void set_lTime(long _lTime) {
		this._lTime = _lTime;
	}
}


@SuppressWarnings("serial")
public class SignLiveChatServlet extends HttpServlet{
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		req.setCharacterEncoding("UTF-8");
		
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        
        String sAction = req.getParameter("action");
        
        if(sAction.compareTo("send_message") == 0)
        {
        	UserService userService = UserServiceFactory.getUserService();
            User user = userService.getCurrentUser();
	        String sMessage = req.getParameter("message");
	        if (sMessage != null) {
	        	
	            if (user != null) {
	            	
	            	ChatLog chat = new ChatLog(user.getNickname(), sMessage, new Date().getTime());
	            	Entity chatlog = new Entity("chatlog");
	            	chatlog.setProperty("username", chat.get_sUserName());
	            	chatlog.setProperty("message", chat.get_sMessage());
	            	chatlog.setProperty("time", chat.get_lTime());
	            	datastore.put(chatlog);	       
	            }
	        }
        }
        else if(sAction.compareTo("get_message") == 0)
        {
	        Vector<ChatLog> aChatLog = new Vector<ChatLog>();
	        
	        long lTime = Long.parseLong(req.getParameter("time"));	        
	        
	        Query query = new Query("chatlog");
	        query.addFilter("time", Query.FilterOperator.GREATER_THAN, lTime);
	        query.addSort("time", Query.SortDirection.ASCENDING);
	        List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
	          
	        for (Entity eChatLog : results) {
	        	lTime = Long.parseLong(eChatLog.getProperty("time").toString());
	        	ChatLog chat = new ChatLog(eChatLog.getProperty("username").toString(), eChatLog.getProperty("message").toString(), lTime);
	        	//chatlog.getProperty("username");
	        	aChatLog.add(chat);
	        	
			}
	        
	        int iCode = aChatLog.isEmpty() ? 0 : 1;
	        ObjectReturn obj = new ObjectReturn(iCode, aChatLog, lTime);
	    	Gson gson = new Gson();            	
			String json = gson.toJson(obj);
			resp.setContentType("text/html;charset=UTF-8");
			resp.getWriter().println(json);
        }
        else if(sAction.compareTo("delete_all") == 0)
        {
        	Query query = new Query("chatlog");
        	List<Entity> results = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
        	for (Entity eChatLog : results) {
        		datastore.delete(eChatLog.getKey());
        	}
        	
        }
    }
}
